package com.example.PDFdemo.pdftest;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class T {
    public void addContent() throws IOException, DocumentException {
        String filePath = "C:\\Users\\admin\\Desktop\\test1.pdf";
        String savePath = "C:\\Users\\admin\\Desktop\\test2.pdf";

        /*BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        Font font = new Font(baseFont);*/
        String fontPath = "static/宋体.ttf";
        BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont, 20, Font.NORMAL, BaseColor.BLACK);
        font.setStyle(0);

        PdfReader reader = new PdfReader(new FileInputStream(filePath));
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(savePath));


        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            PdfContentByte over = stamper.getOverContent(i);
            ColumnText columnText = new ColumnText(over);
            // llx 和 urx  最小的值决定离左边的距离. lly 和 ury 最大的值决定离下边的距离
            //columnText.setSimpleColumn(100, 384, 200, 480);
            Rectangle rectangle = new Rectangle(0, 0, 100f, 100f);


            Phrase phrase = new Phrase("正正正正正", font);
            PdfPCell cell = new PdfPCell(phrase);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);


           //hunk chunk = new Chunk("正正正正正正正正正正正正正正正正正正正正正正正正正正正正正正正正正正正", font);

            //Paragraph elements = new Paragraph(1, new Chunk("111111111111111"));
            // 设置字体，如果不设置添加的中文将无法显示
            //elements.setFont(font);
            //columnText.addElement(elements);

            //columnText.addText(phrase);
            columnText.addElement(cell);
            columnText.setSimpleColumn(rectangle);
            columnText.go();
        }
        stamper.close();
    }

    public static void main(String[] args) throws DocumentException, IOException {
        T t = new T();
        t.addContent();
    }
}
